// 全局变量定义
let canvas;          // 用于存储完整页面截图的画布
let context;         // 画布的2D上下文
let capturing = false;  // 截图状态标志

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('收到消息:', message);
  if (message.action === 'startCapture' && !capturing) {
    console.log('开始滚动截图');
    capturing = true;
    startScrollCapture()
      .then(() => {
        console.log('截图完成');
        sendResponse({ success: true });
      })
      .catch(error => {
        console.error('截图失败:', error);
        sendResponse({ success: false, error: error.message });
      });
    return true;
  } else if (message.action === 'captureVisible' && !capturing) {
    console.log('开始截取当前屏幕');
    capturing = true;
    captureVisibleArea()
      .then(() => {
        console.log('当前屏幕截图完成');
        sendResponse({ success: true });
      })
      .catch(error => {
        console.error('当前屏幕截图失败:', error);
        sendResponse({ success: false, error: error.message });
      });
    return true;
  }
});

// 获取页面实际尺寸
function getPageDimensions() {
  const body = document.body;
  const html = document.documentElement;

  // 获取实际内容宽度（包括溢出部分）
  const width = Math.max(
    html.scrollWidth,
    html.offsetWidth,
    html.clientWidth,
    body.scrollWidth,
    body.offsetWidth
  );

  // 获取实际内容高度（包括溢出部分）
  const height = Math.max(
    html.scrollHeight,
    html.offsetHeight,
    html.clientHeight,
    body.scrollHeight,
    body.offsetHeight
  );

  // 获取视口尺寸
  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;

  // 获取当前滚动位置
  const scrollTop = window.pageYOffset || html.scrollTop;
  const scrollLeft = window.pageXOffset || html.scrollLeft;

  return {
    width,
    height,
    viewportWidth,
    viewportHeight,
    scrollTop,
    scrollLeft
  };
}

// 等待指定时间
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 截取当前可见区域
async function captureVisibleArea() {
  try {
    const dataUrl = await captureViewport();
    downloadImage(dataUrl);
  } catch (error) {
    console.error('截取当前屏幕失败:', error);
    throw error;
  } finally {
    capturing = false;
  }
}

// 开始滚动截图
async function startScrollCapture() {
  try {
    // 获取页面尺寸信息
    const dimensions = getPageDimensions();
    const { width, height, viewportHeight } = dimensions;
    
    console.log('页面尺寸:', dimensions);

    // 创建画布
    canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    context = canvas.getContext('2d');

    // 保存原始滚动位置
    const originalScrollTop = window.scrollY;
    const originalScrollLeft = window.scrollX;

    // 计算滚动步长和总步数
    const scrollStep = Math.floor(viewportHeight * 0.95); // 使用95%视口高度作为步长
    const totalSteps = Math.ceil(height / scrollStep);

    // 滚动到页面顶部
    window.scrollTo(0, 0);
    await sleep(100);

    // 逐步截图
    for (let i = 0; i < totalSteps; i++) {
      const currentScrollTop = i * scrollStep;
      
      // 滚动到指定位置
      window.scrollTo(0, currentScrollTop);
      await sleep(150); // 等待滚动和重绘完成

      // 捕获当前视口
      const dataUrl = await captureViewport();
      const img = await loadImage(dataUrl);

      // 计算当前部分的实际高度
      let currentHeight;
      if (i === totalSteps - 1) {
        // 最后一段
        currentHeight = height - currentScrollTop;
      } else {
        // 普通段
        currentHeight = Math.min(viewportHeight, scrollStep);
      }

      // 计算源图像的裁剪区域
      const sourceY = 0;
      const sourceHeight = Math.min(img.height, currentHeight);

      // 将图像绘制到画布上
      context.drawImage(
        img,
        0,
        sourceY,
        img.width,
        sourceHeight,
        0,
        currentScrollTop,
        width,
        sourceHeight
      );

      console.log(`完成第 ${i + 1}/${totalSteps} 段截图，位置: ${currentScrollTop}px, 高度: ${sourceHeight}px`);
    }

    // 生成并保存截图
    const fullPageDataUrl = canvas.toDataURL('image/png');
    downloadImage(fullPageDataUrl);

    // 恢复原始滚动位置
    window.scrollTo(originalScrollLeft, originalScrollTop);

  } catch (error) {
    console.error('截图过程出错:', error);
    throw error;
  } finally {
    capturing = false;
  }
}

// 捕获当前视口内容
function captureViewport() {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage(
      { action: 'captureTab' },
      response => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
          return;
        }
        if (response && response.error) {
          reject(new Error(response.error));
          return;
        }
        if (response && response.dataUrl) {
          resolve(response.dataUrl);
        } else {
          reject(new Error('未收到截图数据'));
        }
      }
    );
  });
}

// 加载图像
function loadImage(dataUrl) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = reject;
    img.src = dataUrl;
  });
}

// 下载图像
function downloadImage(dataUrl) {
  const link = document.createElement('a');
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  link.download = `screenshot_${timestamp}.png`;
  link.href = dataUrl;
  link.click();
}
